<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home/Home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>容器信息</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 信息面板 -->
        <el-card class="cardBox">
            <!-- 标题 -->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold; font-size: large;">容器信息</span>
            </div>
            <!-- 控制按钮 -->
            <div style="margin-bottom: 10px; font-size: larger; float: left;">
                <div v-if="containerInfo.status == 'running'" style="font-size:large;font-weight: bold; color: gray;">
                    控制容器：
                    <el-tooltip effect="dark" content="暂停容器" placement="top">
                        <el-button type="warning" icon="el-icon-video-pause" circle
                            @click="containerOperation('pause')"></el-button>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="停止容器" placement="top">
                        <el-button style="margin-left: -5px;" type="info" icon="el-icon-circle-close" circle
                            @click="containerOperation('stop')"> </el-button>
                    </el-tooltip>
                </div>
                <div v-if="containerInfo.status == 'paused'">
                    控制容器：
                    <el-tooltip effect=" dark" content="运行容器" placement="top">
                        <el-button type="success" icon="el-icon-video-play" circle
                            @click="containerOperation('start')"></el-button>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="取消暂停容器" placement="top">
                        <el-button style="margin-left: -5px;" type="warning" icon="el-icon-video-pause" circle
                            @click="containerOperation('unpause')"></el-button>
                    </el-tooltip>
                    <el-tooltip effect="dark" content="停止容器" placement="top">
                        <el-button style="margin-left: -5px;" type="info" icon="el-icon-circle-close" circle
                            @click="containerOperation('stop')"></el-button>
                    </el-tooltip>

                </div>
                <div v-if="containerInfo.status == 'exited'">
                    控制容器：
                    <el-tooltip effect="dark" content="运行容器" placement="top">
                        <el-button type="success" icon="el-icon-video-play" circle
                            @click="containerOperation('start')"></el-button>
                    </el-tooltip>
                </div>
            </div>
            <div style="float: right;">
                <el-tooltip effect="dark" content="重命名容器" placement="bottom">
                    <el-button type="primary" icon="el-icon-edit" circle @click="renameDrawer.show = true"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="删除容器" placement="bottom">
                    <el-button style="margin-left: -5px;" type="danger" icon="el-icon-delete" circle
                        @click="removeDrawer.show = true"></el-button>
                </el-tooltip>
            </div>
            <!-- 信息表 -->
            <el-descriptions class="margin-top" column="5" border>
                <el-descriptions-item>
                    <template slot="label">
                        容器名称
                    </template>
                    {{ containerInfo.name }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        容器ID
                    </template>
                    {{ containerInfo.hostName }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        镜像名称
                    </template>
                    {{ containerInfo.image }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        创建时间
                    </template>
                    {{ containerInfo.createTime }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        状态
                    </template>
                    <div v-if="containerInfo.status == 'running'">
                        <el-tag type="success" effect="dark">Running</el-tag>
                    </div>
                    <div v-if="containerInfo.status == 'exited'">
                        <el-tag type="danger" effect="dark">Exited</el-tag>
                    </div>
                    <div v-if="containerInfo.status == 'paused'">
                        <el-tag type="warning" effect="dark">Paused</el-tag>
                    </div>
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        工作目录
                    </template>
                    {{ containerInfo.workingData }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        端口映射
                    </template>
                    {{ containerInfo.ports }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        数据卷绑定
                    </template>
                    {{ containerInfo.hostBinds }}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions class="margin-top" column="2" border>
                <el-descriptions-item>
                    <template slot="label">
                        cmd命令
                    </template>
                    {{ containerInfo.cmd }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        entrypoint
                    </template>
                    {{ containerInfo.entrypoint }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        环境参数
                    </template>
                    {{ containerInfo.env }}
                </el-descriptions-item>


            </el-descriptions>
            <el-divider></el-divider>
            <!-- 容器终端 -->
            <a style="font-weight: bolder; font-size:larger;">终端信息:</a>
            <el-row type="flex" class="row-bg" justify="center" style=" margin-top: 20px;">
                <el-col :span="10">
                    <div>
                        <el-card shadow="never" class="termianlBox">
                            <div slot="header" class="clearfix">
                                <span style="font-size: larger;font-weight: bold;">远程终端</span>
                                <el-button style="float: right; padding: 3px 0" type="text" v-if="terminal.open == false"
                                    @click="openTerminal()"><i class="el-icon-video-play"></i>开启</el-button>
                                <el-button style="float: right; padding: 3px 0" type="text" v-else
                                    @click="closeTerminal()"><i class="el-icon-circle-close"></i>关闭</el-button>
                            </div>
                            <!--  margin-top: -3%;margin-left: -3%;width: 106%;  -->
                            <div id="terminal" style="background-color: red;height: 400px; width: 300px;" />
                        </el-card>
                    </div>
                </el-col>
                <el-col :span="2">
                    <div class="vertical-line"></div>
                </el-col>
                <el-col :span="10">
                    <div>
                        <el-card shadow="never" class="termianlBox">
                            <div slot="header" class="clearfix">
                                <span style="font-size: larger;font-weight: bold;">操作容器</span>
                                <el-button style="float: right; padding: 3px 0" type="text" v-if="attach.open == false"
                                    @click="openAttach()"><i class="el-icon-video-play"></i>开启</el-button>

                                <el-button style="float: right; padding: 3px 0" type="text" v-else @click="closeAttach()"><i
                                        class="el-icon-circle-close"></i>关闭</el-button>
                            </div>
                            <el-input id="attachTextrae" type="textarea" :rows="18" v-model="attach.textarea"
                                style="margin-top: -3%;margin-left: -3%;width: 106%;" readonly resize="none" outline="none">
                            </el-input>
                            <el-row type="flex" class="row-bg" justify="center"
                                style="margin-top: 3px;margin-left: -3%;width: 106%;">
                                <el-col :span="21">
                                    <el-input v-model="attach.sendMassage"></el-input>
                                </el-col>
                                <el-col :span="3">
                                    <el-button type="primary" style="margin-left: 5%;" @click="sendAttach()">发送</el-button>
                                </el-col>
                            </el-row>
                        </el-card>
                    </div>
                </el-col>
            </el-row>
            <el-divider></el-divider>
            <!-- 容器信息监控 -->
            <a style="font-weight: bolder; font-size:larger;">资源监控:</a>
            <el-row :gutter="24" style=" margin-top: 20px;">
                <el-col :span="8">
                    <div id="main" style="width: 100%;height:300px;" ref="cpuLineChart"></div>
                </el-col>
                <el-col :span="8">
                    <div id="main" style="width: 100%;height:300px;" ref="memoryLineChart"></div>
                </el-col>
                <el-col :span="8">
                    <div id="main" style="width: 100%;height:300px;" ref="ioLineChart"></div>
                </el-col>
            </el-row>
        </el-card>
        <!-- 重命名容器窗口 -->
        <el-drawer title="重命名容器" :visible.sync="renameDrawer.show">
            <el-form label-width="100px">
                <el-form-item label="新名称:">
                    <el-input v-model="renameDrawer.name" style="width: 80%;"></el-input>
                </el-form-item>
            </el-form>
            <div style="position: fixed;bottom: 10px;right: 20px;">
                <el-button @click="renameDrawer.show = false">取 消</el-button>
                <el-button type="primary" @click="containerOperation('rename')" :loading="loading">{{ loading ? '提交中 ...'
                    : '重命名' }}</el-button>
            </div>
        </el-drawer>
        <!-- 删除容器窗口 -->
        <el-drawer title="删除容器" :visible.sync="removeDrawer.show">
            <el-form label-width="100px">
                <el-form-item label="强制删除:">
                    <el-radio-group v-model="removeDrawer.force">
                        <el-radio :label="true" border>是</el-radio>
                        <el-radio :label="false" border>否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="删除数据卷:">
                    <el-radio-group v-model="removeDrawer.removeVolume">
                        <el-radio :label="true" border>是</el-radio>
                        <el-radio :label="false" border>否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div style="position: fixed;bottom: 10px;right: 20px;">
                <el-button @click="removeDrawer.show = false">取 消</el-button>
                <el-button type="danger" @click="containerOperation('remove')" :loading="loading" disabled>{{ loading ?
                    '提交中 ...'
                    : '删 除' }}</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import echarts from 'echarts'
import { infoContainer, startContainer, stopContainer, pauseContainer, unpauseContainer, renameContainer, removeContainer } from '../../api/userMG';
// import 'xterm/css/xterm.css';
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { AttachAddon } from 'xterm-addon-attach'
export default {
    name: "ContainerInfo",
    data() {
        //数据  
        return {
            key: 0,
            containerId: 0,
            containerInfo: {},
            chartSocket: null,
            cpuLineChart: null,
            cpuLineChartOption: {},
            memoryLineChart: null,
            memoryLineChartOption: {},
            ioLineChart: null,
            ioLineChartOption: {},
            timeData: [],
            attach: {
                open: false,
                textarea: '',
                attachSocket: null,
                sendMassage: '',
            },
            terminal: {
                open: false,
                socket: null,
                term: null,
            },
            renameDrawer: {
                show: false,
                name: ''
            },
            removeDrawer: {
                show: false,
                force: false,
                removeVolume: false,
            }
        };
    },
    watch: {
        'attach.textarea'(newvalue) {
            this.textareaToDown()
        }
    },
    methods: {
        getBaseData() {
            var param = {
                key: this.key,
                id: this.containerId
            }
            if (param.key == 0 || param.containerId == 0) {
                return;
            }
            infoContainer(param).then(res => {
                if (res.code == 0) {
                    this.containerInfo = res.data
                    this.renameDrawer.name = res.data.name
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        textareaToDown() {
            const textarea = document.getElementById('attachTextrae');
            textarea.scrollTop = textarea.scrollHeight;
        },
        openCpuLineChart() {
            const cpuLineChart = echarts.init(this.$refs.cpuLineChart);
            this.cpuLineChartOption = {
                title: {
                    left: 'center',
                    text: 'CPU使用率',
                    titleStyle: {
                        color: 'black'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: '{value} %'//纵坐标百分比
                    }
                },
                series: [
                    {
                        data: [],
                        type: 'line',
                        smooth: true
                    }
                ],
            }
            this.cpuLineChart = cpuLineChart
            cpuLineChart.setOption(this.cpuLineChartOption)
        },
        openMemoryLineChart() {
            const memoryLineChart = echarts.init(this.$refs.memoryLineChart);
            this.memoryLineChartOption = {
                title: {
                    left: 'center',
                    text: '内存使用率',
                    titleStyle: {
                        color: 'black'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: '{value} %'//纵坐标百分比
                    }
                },
                series: [
                    {
                        data: [],
                        type: 'line',
                        smooth: true
                    }
                ],
            }
            this.memoryLineChart = memoryLineChart
            memoryLineChart.setOption(this.memoryLineChartOption)
        },
        openIOLineChart() {
            const ioLineChart = echarts.init(this.$refs.ioLineChart);
            this.ioLineChartOption = {
                title: {
                    left: 'center',
                    text: 'I/O网络流量(KB)',
                    titleStyle: {
                        color: 'black'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value',
                },
                series: [
                    {
                        data: [],
                        type: 'line',
                        smooth: true
                    }
                ]
            }
            this.ioLineChart = ioLineChart
            ioLineChart.setOption(this.ioLineChartOption)
        },
        openChartWebSoket() {
            var params = {
                key: this.key,
                id: this.containerId
            }
            if (params.id == 0 && params.id == 0) {
                return
            }
            const chartSocket = new WebSocket('ws://localhost:8081/api/ws/stats/' + params.key + '/' + params.id);
            this.chartSocket = chartSocket
            chartSocket.onopen = () => {
                console.log('[chart]WebSocket连接已建立');
            }
            chartSocket.onmessage = (event) => {
                let data = JSON.parse(event.data);
                if (this.timeData.length == 10) {
                    this.timeData.shift();
                }
                this.timeData.push(data.createTime)
                this.cpuLineChartOption.xAxis.data = this.timeData
                if (this.cpuLineChartOption.series[0].data.length == 10) {
                    this.cpuLineChartOption.series[0].data.shift()
                }
                this.cpuLineChartOption.series[0].data.push(data.cpuUsage)
                this.cpuLineChart.setOption(this.cpuLineChartOption)

                this.memoryLineChartOption.xAxis.data = this.timeData
                if (this.memoryLineChartOption.series[0].data.length == 10) {
                    this.memoryLineChartOption.series[0].data.shift()
                }
                this.memoryLineChartOption.series[0].data.push(data.memoryUsage)
                this.memoryLineChart.setOption(this.memoryLineChartOption)
                this.ioLineChartOption.xAxis.data = this.timeData
                var size = data.networkUsage.length
                for (var i = 0; i < size; i++) {
                    if (this.ioLineChartOption.series[i].data.length == 10) {
                        this.ioLineChartOption.series[i].data.shift()
                    }
                    this.ioLineChartOption.series[i].data.push(data.networkUsage[i].kiloByte)
                }
                this.ioLineChart.setOption(this.ioLineChartOption)
            }
        },
        openAttach() {
            var params = {
                key: this.key,
                id: this.containerId
            }
            this.attach.open = true
            this.attach.textarea = ''
            const attachSocket = new WebSocket('ws://localhost:8081/api/ws/attach/' + params.key + '/' + params.id);
            this.attach.attachSocket = attachSocket
            attachSocket.onopen = () => {
                console.log('[attach]WebSocket连接已建立');
            }
            attachSocket.onmessage = (event) => {
                this.attach.textarea += event.data + '\n';
            }
        },
        closeAttach() {
            console.log('11111');
            this.attach.open = false
            this.attach.textarea = ''
            this.attach.attachSocket.close()
        },
        sendAttach() {
            this.attach.attachSocket.send(this.attach.sendMassage)
            this.attach.sendMassage = ''
            this.textareaToDown()
        },
        openTerminal() {
            var params = {
                key: this.key,
                id: this.containerId
            }
            const term = new Terminal();
            const fitAddon = new FitAddon();
            const socket = new WebSocket('ws://localhost:8081/api/ws/term/' + params.key + '/' + params.id);
            
            const attachAddon = new AttachAddon(socket); // 建立websocket链接
            term.loadAddon(attachAddon);
            term.loadAddon(fitAddon);

            term.open(document.getElementById('terminal'));
            setTimeout(() => {
                this.fitAddon.fit()
            }, 60) // 而且不能是0 ,xterm 生成时间在2ms左右
            term.focus();
            //socket.onopen = () => { socket.send('>>>\n'); }; // 当连接建立时向终端发送一个换行符，不这么做的话最初终端是没有内容的，输入换行符可让终端显示当前用户的工作路径
            term.prompt = _ => {
        term.write("\r\n\x1b[33m$\x1b[0m ")
      }
            window.onresize = function () { // 窗口尺寸变化时，终端尺寸自适应
                fitAddon.fit();
            };
            this.terminal.term = term
            this.terminal.socket = socket
            this.terminal.open = true
        },
        closeTerminal() {
            this.terminal.open = false
            this.terminal.socket.close()
            this.terminal.term.dispose()
        },
        containerOperation(operation) {
            var params = {
                key: this.key,
                id: this.containerId
            }
            var rename = {
                key: this.key,
                id: this.containerId,
                name: this.renameDrawer.name
            }
            var remove = {
                key: this.key,
                id: this.containerId,
                force: this.removeDrawer.force,
                removeVolume: this.removeDrawer.removeVolume,
            }
            if (operation == 'start') {
                startContainer(params).then(res => {
                    if (res.code == 0) {
                        this.$message.success("启动容器成功！")
                        this.getBaseData()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else if (operation == 'stop') {
                stopContainer(params).then(res => {
                    if (res.code == 0) {
                        this.$message.success("停止容器成功！")
                        this.getBaseData()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else if (operation == 'pause') {
                pauseContainer(params).then(res => {
                    if (res.code == 0) {
                        this.$message.success("暂停容器成功！")
                        this.getBaseData()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else if (operation == 'unpause') {
                unpauseContainer(params).then(res => {
                    if (res.code == 0) {
                        this.$message.success("取消暂停容器成功！")
                        this.getBaseData()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else if (operation == 'rename') {
                if (rename.name == this.containerInfo.name) {
                    this.$message.error("请填写新名称后操作！")
                    return
                }
                renameContainer(rename).then(res => {
                    if (res.code == 0) {
                        this.renameDrawer.show = false
                        this.$message.success("重命名容器成功！")
                        this.getBaseData()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            } else if (operation == 'remove') {
                removeContainer(remove).then(res => {
                    if (res.code == 0) {
                        this.removeDrawer.show = false
                        this.$message.success("删除容器成功！")
                        this.$router.push({ path: '/container/containersManagement' });
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            }
        },

    },
    mounted() {
        this.openCpuLineChart()
        this.openMemoryLineChart()
        this.openIOLineChart()
        this.openChartWebSoket()
    },
    created() {
        this.key = this.$route.query.key
        this.containerId = this.$route.query.id
        this.getBaseData()
    },
    beforeDestroy() {
        this.attach.attachSocket.close()
        this.chartSocket.close()
    },
};
</script>
<style scoped>
.cardBox {
    margin-top: 30px;
    width: 95%;
    height: 100%;
    margin-left: 1%;

}

.vertical-line {
    margin-left: 50%;
    width: 1px;
    height: 100%;
    /* 设置分割线的高度 */
    background-color: rgb(155, 154, 154);
    /* 设置分割线的颜色 */
}

.termianlBox {
    width: 100%;
    height: 500px;
    background-color: rgb(250, 250, 250);
}

.startBtn {
    float: right;
    margin-bottom: 5px;
}

input {
    background-color: black;
}
</style>
